<template>
  <div id="AppGrayPublish" ref="grayPublish">
    <h1 class="title">灰度用户组设置</h1>
    <div class="container-box">
    <div class="toolbar">
      <el-button @click="addGruop" type="primary" size="mini">增加</el-button>
      <el-button @click="modifyGruop" type="primary" size="mini">编辑</el-button>
      <el-button @click="deleteGruop" type="primary" size="mini">删除</el-button>
    </div>
    <div class="main-cont">
      <el-table v-loading="loading" :data="tableData" :height="height" highlight-current-row @current-change="handleCurrentChange">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="groupName" label="灰度组" min-width="120"></el-table-column>
        <el-table-column label="工作区名称"></el-table-column>
        <el-table-column label="参数属性"></el-table-column>
        <!-- <el-table-column prop="paramInfo" label="上传方式" min-width="120"></el-table-column> -->
        <el-table-column prop="paramInfo" label="数据" min-width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.paramInfo">{{scope.row.paramInfo}}</span>
            <span v-else>待绑定</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="bindUser(scope.row)" type="text" size="mini">
              绑定用户
            </el-button>
            <el-button @click="clearWs(scope.row)" type="text" size="mini">清空</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="currentChange"
        :current-page="currentPage"
        :page-size="pagesize"
        layout="total, prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
     </div>
    <!--下面放弹框 增删改-->
    <el-dialog :title="title === 'ADD' ? '新增用户组' : '修改用户组'" :visible.sync="dialogFlag" width="900px" top="200px">
      <el-form :model="groupData" ref="groupForm" :rules="rules" label-position="right" label-width="140px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="灰度组名称" prop="groupName">
              <el-input v-model="groupData.groupName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row class="f-rt">
        <el-button size="mini" @click="rest">重置</el-button>
        <el-button size="mini" @click="close">关闭</el-button>
        <el-button type="primary" size="mini" @click="submit">确定</el-button>
      </el-row>
    </el-dialog>
        <!-- 用户绑定的弹框 -->
    <el-dialog title="添加用户" :visible.sync="bindDialogFlagUser" width="900px" top="200px">
      <el-row :gutter="30">
        <el-col :span="24">
          <el-radio-group v-model="condition">
            <el-radio :label="1">按指定参数添加</el-radio>
            <el-radio :label="2">按指定用户添加</el-radio>
            <el-radio :label="3">按时间窗灰度添加</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <el-form label-position="right" label-width="110px" :rules="DialogRules">
        <template v-if="condition === 1">
          <el-row :gutter="20" type="flex" justifu="center">
            <el-col :span="8" :offset="3">
              <el-select multiple placeholder="选择机型" v-model="searchDataGroup.deviceType" popper-class="zIndex-popper">
                <el-option v-for="item in deviceTypeLsit" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select multiple placeholder="选择版本" v-model="searchDataGroup.systemVersion" popper-class="zIndex-popper">
                <el-option v-for="item in versionNoList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select placeholder="选择应用版本" v-model="searchDataGroup.appVersion" popper-class="zIndex-popper">
                <el-option v-for="item in appNoList" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                </el-option>
              </el-select>
            </el-col>
            <!-- <el-col :span="4">
              <el-button icon="el-icon-search" size="mini" type="primary" @click="searchUser"></el-button>
            </el-col> -->
          </el-row>
        </template>
        <template v-else-if="condition === 2">
          <el-row>
            <el-col :span="8">
              <el-form-item label="上传文件" prop="fileList" >
                <el-upload
                  ref="uploadCom"
                  :data="uploadParams"
                  action="/api/insertUserGroupByExcel"
                  name="file"
                  :on-success="successUpload"
                  :on-error="errFun"
                  :auto-upload="true">
                  <el-button type="primary" size="mini" @click="giveData">选择文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-table :data="unBindUserData" @select-all="unBIndSelectAll" @select="changeData" v-loading="userLoading">
            <!-- <el-table-column type="selection" width="55"></el-table-column> -->
            <el-table-column prop="deviceType" label="设备类型" min-width="120"></el-table-column>
            <el-table-column prop="id" label="用户ID" min-width="120"></el-table-column>
            <el-table-column prop="last_login_time" label="最后登入时间" min-width="120"></el-table-column>
            <el-table-column prop="systemType" label="系统类型" min-width="120"></el-table-column>
          </el-table>
          <el-pagination
            @current-change="dialogCurrentChange"
            :current-page="dialogCurrentPage"
            :page-size="5"
            layout="total, prev, pager, next"
            :total="dialogTotalCount">
          </el-pagination>
        </template>
        <template v-else>
          <el-form-item label="结束时间">
            <el-col :span="9">
              <el-date-picker v-model="grayEndTime" type="datetime" placeholder="选择日期时间" popper-class="zIndex-popper" size="mini"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="灰度终端数 :">
            <el-col :span="9">
              <el-input type="text" size="mini"></el-input>
            </el-col>
          </el-form-item>
        </template>
      </el-form>
      <el-row class="f-rt">
        <el-button size="mini" @click="closeUser">关闭</el-button>
        <el-button type="primary" size="mini" @click="bindUserSubmit">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
  import { VHeader } from '../../../../components'
  import '../../../../assets/css/mixinParameterManager.styl'
  import api from '../../../../api/url'
  import ajax from '../../../../api/ajax/ajax'
  import rules from '../../js/formRules'
  import { mapGetters } from 'vuex'

  export default {
    name: 'app-gray-publish',
    components: {
      VHeader
    },
    data () {
      return {
        dialogFlag: false,
        bindDialogFlagUser: false,
        bindDialogFlagApp: false,
        condition: 1, // 按条件筛选
        height: null,
        tableData: [],
        currentRowData: {},
        dialogTotalCount: '', // 弹框分页的总数
        dialogPagesize: '', // 弹框分页的页码
        dialogCurrentPage: 1, // 弹框的当前页数
        loading: true,
        upLoadParaList: [], // 文件上传参数内容
        searchDataGroup: {
          deviceType: [],
          systemVersion: []
        },
        deviceTypeLsit: [],
        versionNoList: [],
        appNoList: [],
        grayEndTime: '',
        uploadParams: {
          id: '',
          groupName: ''
        },
        title: '',
        saveCurrentGroup: '',
        groupData: {
          groupName: '',
          groupType: 'app'
        },
        // bindUserData: [],
        unBindUserData: [],
        // userBindStatus: '',
        appBindStatus: '',
        // boundedAppList: [],
        systemType: 'Android',
        userLoading: false,
        selectUserData: [],
        selectAppData: [],
        rules: rules.whiteList,
        DialogRules: rules.DialogRules,
        pickerOptions1: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          },
          shortcuts: [{
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }]
        },
        currentPage: 1,
        pagesize: 10,
        totalCount: 0
      }
    },
    watch: {
      bindDialogFlagApp (val) {
        this.selectAppData = []
        this.systemType = 'Android'
      },
      bindDialogFlagUser (val) {
        this.selectUserData = []
      },
      dialogFlag (bol) {
        if (bol === false) {
          for (let key in this.groupData) {
            if (key !== 'groupType') {
              delete this.groupData[key]
            }
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'workspaceId'
      ])
    },
    methods: {
      handleRepealClick (scope) {
        this.$confirm('是否撤销发布', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            groupId: scope.groupId,
            groupName: scope.groupName,
            groupType: scope.groupType,
            published: false
          }
          this.handleRepeal(params)
        }).catch(() => {})
      },
      handleRepeal (params) {
        ajax.post(api.MODIFY_GROUP, params).then(res => {
          if (res.data === 1) {
            this.$message({
              type: 'success',
              message: '撤销成功!'
            })
            this.queryGroupList()
          }
        })
      },
      handleInsertWork (params) {
        ajax.post(api.MODIFY_GROUP, params).then(res => {
          if (res.data === 1) {
            this.$message({
              type: 'success',
              message: '发布成功!'
            })
            this.queryGroupList()
          }
        })
      },
      // 点上传把工作组以及ID赋值
      giveData () {
        this.uploadParams.id = this.currentRowData.id
        this.uploadParams.groupName = this.currentRowData.groupName
      },
      // 上传成功
      successUpload (response, file, fileList) {
        this.$message({
          type: 'success',
          message: '文件上传成功' + response.msg
        })
        this.userLoading = true
        this.$refs.uploadCom.clearFiles()
        // this.dialogQueryList()
        this.requestUserList()
        this.queryGroupList()
      },
      errFun (err) {
        this.$message({
          type: 'success',
          message: err
        })
      },
      // ********************** 灰度组增删改查 *******************************
      // 增加灰度分组
      addGruop () {
        this.title = 'ADD'
        this.dialogFlag = true
      },
      // 灰度组单选
      handleCurrentChange (currentRow) {
        this.saveCurrentGroup = currentRow
      },
      // 灰度组编辑
      modifyGruop () {
        this.title = 'MODIFY'
        if (this.saveCurrentGroup) {
          this.dialogFlag = true
          this.groupData = {...this.saveCurrentGroup}
        } else {
          this.$alert('请选择一个用户分群组', '温馨提示')
        }
      },
      // 删除灰度组
      deleteGruop () {
        if (this.saveCurrentGroup) {
          this.$confirm('确定要删除该项吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let arr = []
            arr.push(this.saveCurrentGroup.groupId)
            ajax.post(api.DELETE_GROUP, { groupIds: arr, groupType: 'app' }).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.queryGroupList()
            })
          })
        } else {
          this.$alert('请选择一个用户分群组', '温馨提示')
        }
      },
      // 分页
      currentChange (val) {
        this.currentPage = val
        this.queryGroupList(val)
      },
      dialogCurrentChange (val) {
        this.requestUserList(val)
      },
      // 灰度组的新增或修改的重置
      rest () {
        if (this.title === 'ADD') {
          this.groupData.groupName = ''
          this.$refs.groupForm.clearValidate()
        } else {
          this.groupData = {...this.saveCurrentGroup}
          this.$refs.groupForm.clearValidate()
        }
      },
      // 灰度组的新增或修改的关闭
      close () {
        this.dialogFlag = false
        this.$refs.groupForm.clearValidate()
      },
      // 灰度组新增或修改的确定
      submit () {
        this.$refs.groupForm.validate(valid => {
          if (valid) {
            this.groupData['groupType'] = 'app'
            if (this.title === 'ADD') {
              ajax.post(api.ADD_GROUP, this.groupData).then(res => {
                this.$message({
                  type: 'success',
                  message: '增加成功'
                })
                this.queryGroupList(this.currentPage)
                this.dialogFlag = false
                this.groupData.groupName = ''
                this.$refs.groupForm.clearValidate()
              }).catch(err => {
                console.info(err)
              })
            } else {
              ajax.post(api.MODIFY_GROUP, this.groupData).then(res => {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.queryGroupList(this.currentPage)
                this.dialogFlag = false
                this.groupData.groupName = ''
                this.$refs.groupForm.clearValidate()
              }).catch(err => {
                console.info(err)
              })
            }
          }
        })
      },
      // ********************* 用户绑定 ********************
      // 用户绑定或解除绑定提交
      bindUserSubmit () {
        let postParam = {param: {}}
        postParam.param.deviceType = this.searchDataGroup.deviceType
        postParam.param.systemVersion = this.searchDataGroup.systemVersion
        postParam.groupId = this.currentRowData.id
        postParam.groupName = this.currentRowData.groupName
        ajax.post(api.ADD_USER_USERGROUP, postParam).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.queryGroupList()
          this.bindDialogFlagUser = false
        })
      },
      // 查询当前组内未绑定的所有用户列表
      bindUser (para) {
        this.bindDialogFlagUser = true
        this.currentRowData = para
        // this.userBindStatus = 'bind'
        this.unBindUserData = []
        // this.userLoading = true
        this.requestList()
        this.requestUserList(1, 5)
      },
      // 用户绑定或解除用户绑定弹框关闭
      closeUser () {
        this.uploadParams.groupId = ''
        this.uploadParams.groupName = ''
        this.searchDataGroup = ''
        this.bindDialogFlagUser = false
      },
      // 用户勾选改变
      changeData (selection) {
        this.selectUserData = selection.map(item => item)
      },
      // 解绑用户全选
      unBIndSelectAll (allData) {
        this.selectUserData = allData.map(item => item)
      },
      // 清空
      clearWs (rowGroupId) {
        console.log(rowGroupId)
        this.$confirm('是否确定清空', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax.post(api.DELETE_USER_USERGROUP, {groupId: rowGroupId.id}, true).then(res => {
            this.$message({
              type: 'success',
              message: '灰度组已清空用户'
            })
            this.queryGroupList()
          }).then(err => {
            this.$message({
              type: 'error',
              message: err.message
            })
          })
        })
      },
      closeApp () {
        this.bindDialogFlagApp = false
      },
      // 灰度组列表
      queryGroupList (pageNo = 1, pageSize = 5) {
        this.tableData = []
        ajax.post(api.SEARCH_LIST_GROUP, {groupType: 'app', pageNo: pageNo, pageSize: pageSize}).then(res => {
          console.log(res)
          if (res.data.list.length > 0) {
            this.tableData = res.data.list
            this.totalCount = res.data.total
          }
          this.loading = false
        })
      },
      // 弹框列表
      // dialogQueryList (pNo) {
      //   // this.currentRowDataPage = Object.assign(this.currentRowData, { pageNo: pNo, pageSize: 5 })
      //   // this.currentRowDataPage =
      //   this.requestList(this.currentRowDataPage)
      // },
      // 请求列表
      requestUserList (pageNo = 1, pageSize = 5) {
        let postParamsObj = Object.assign(this.currentRowData, {pageNo: pageNo, pageSize: pageSize})
        console.log(postParamsObj)
        ajax.post(api.SEARCH_CURRENT_ALL_USER, postParamsObj).then(res => {
          this.unBindUserData = res.data.list
          this.userLoading = false
          this.dialogTotalCount = res.data.total
        })
      },
      requestList () {
        ajax.post(api.LIST_PARAM, {paramType: 'device_type'}).then(res => {
          let arr = res.data.map(item => {
            return {value: item, label: item}
          })
          this.deviceTypeLsit = arr
        })
        ajax.post(api.LIST_PARAM, {paramType: 'system_version'}).then(res => {
          let arr = res.data.map(item => {
            return {value: item, label: item}
          })
          this.versionNoList = arr
        })
        ajax.get(api.VERSIONS).then(res => {
          if (res.Version) {
            let arr = res.Version.map(item => {
              if (item.ClientType === '0') {
                item.ClientType = 'Android'
              } else {
                item.ClientType = 'Ios'
              }
              return {value: item.ClientVersionId, label: item.ClientType}
            })
            this.appNoList = arr
          }
        })
      }
    },
    created () {
      this.queryGroupList()
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">
  #AppGrayPublish
    height 100%
    overflow hidden
    .container-box
      height 100%
      overflow auto
    .toolbar
      height 58px
      background #ffffff
      line-height 58px
      padding 0 15px
      margin 10px 0 10px 10px
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .main-cont
      margin 10px 0 0 10px
      height calc(100% - 78px)
    .el-dialog
      .el-dialog__body
        padding-bottom 70px !important
        .el-radio-group
          float right
          .el-radio-group
            .el-radio-button__inner
              padding 6px 15px
        .detailListStyle
          width 860px
          text-align center
          word-break break-all
    .f-rt
      margin-top 15px
      float right
    // .el-button--text
    //   width 30px
    .el-row
      margin-bottom 20px
    .el-date-editor
      width auto !important
</style>
